package com.refusea.train.domain.helper

import com.refusea.commons.utils.Sn
import com.refusea.train.domain.cache.SchoolCache
import com.refusea.train.domain.cache.TokenCache
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.domain.req.LoginReq
import com.refusea.train.mapper.UserMapper
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component

/**
 * @author Zhang Yan 2024/3/24
 **/
@Component
class LoginHelper(
    private val userMapper: UserMapper,
    private val passwordEncoder: PasswordEncoder,
    private val tokenCache: TokenCache,
    private val schoolCache: SchoolCache,
) {
    fun login(req: LoginReq): String {
        val user = userMapper.selectByLoginId(req.loginId) ?: throw BizEx.of("登录 ID 不存在")
        if (!passwordEncoder.matches(req.password, user.password)) {
            throw BizEx.of("密码错误")
        }
        user.school = schoolCache.get(user.schoolId)?.name

        val token = Sn.next()
        tokenCache.put(token, user)
        return token
    }
}
